<template>
  <div style="background-color: #F5F5F5; height: 870px" class="awsCenter">
    <div style="background-color: white; width: 70%; height: 95%; border-radius: 25px; padding: 20px;">
      <h2 style="margin-bottom: 30px">我的预约记录</h2>
      <el-table :data="appointments" style="width: 100%" height="600px" :row-style="{ height: '80px' }">
        <el-table-column prop="name" label="来访者姓名" />
        <el-table-column prop="phone" label="手机号" width="120"/>
        <el-table-column prop="weekend" label="预约星期" />
        <el-table-column prop="times" label="咨询时间段" width="150"/>
        <el-table-column prop="room" label="地点" />
        <el-table-column prop="status" label="预约状态">
          <template v-slot="{ row }">
            <el-tag :type="formatStatus(row)">{{row.status}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdat" label="预约时间" width="200"/>

        <el-table-column label="操作">
          <template v-slot="{ row }">
            <div v-if="row.status!='已完成'">
              <el-button
                  :disabled="row.status!='已预约'"
                  link
                  type="primary"
                  @click="completeAppointment(row.appointmentid)"
              >
                完成
              </el-button>
              <el-button
                  :disabled="row.status!='已预约'"
                  link
                  type="danger"
                  @click="showCancelDialog(row)"
              >
                取消
              </el-button>
            </div>
            <div v-else>
              <el-button link type="primary" @click="selectFeed(row)">查看反馈</el-button>
            </div>

          </template>
        </el-table-column>
      </el-table>

      <div class="awsCenter" style="margin-top: 20px">
        <el-pagination
            v-model:current-page="currentPage1"
            :page-size="10"
            :size="size"
            :disabled="disabled"
            :background="background"
            layout="total, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>

      <el-dialog :title="`取消预约 - ${selectedAppointment?.name}`" v-model="cancelDialogVisible" width="500">
        <el-input
            type="textarea"

            placeholder="请输入取消原因"
            v-model="remark"
            rows="4"
        />
        <span style="margin-top: 20px" slot="footer" class="dialog-footer">
          <el-button @click="cancelDialogVisible = false" plain color="#ec8061">取 消</el-button>
          <el-button color="#ec8061" type="primary" @click="cancelAppointment(selectedAppointment.appointmentid)"><text style="color: white">确 定</text></el-button>
        </span>
      </el-dialog>


      <el-dialog
          v-model="showComplete"
          title="来访者评估"
          width="500"
          align-center
      >
        <el-form :data="assessForm" label-position="top">
          <el-form-item label="问题点">
            <el-input :rows="4" v-model="assessForm.problem" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="解决方案">
            <el-input :rows="4" v-model="assessForm.plan" type="textarea"></el-input>
          </el-form-item>
        </el-form>

        <template #footer>
          <div class="dialog-footer">
            <el-button color="#ec8061" type="primary" @click="compete">
              <text style="color: white">提 交</text>
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import type {ComponentSize} from 'element-plus'
import {ElMessage} from "element-plus";

import {onMounted, onUnmounted, ref} from 'vue';
import {cancelService, completeService, getAppByUserIdService} from "@/api/appointment.js";
import {useUserStore} from "@/stores/user/user.js";
import router from "@/router";

const currentPage1 = ref(1)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const total=ref(0)




const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = async (val: number) => {
  const body={
    current:currentPage1.value,
    pageSize:10,
    userid:parseInt(userStore.user.userid)
  }

  let res=await getAppByUserIdService(body)
  if (res.code===200){
    appointmentsFormat(res.data.data)
    total.value=res.data.total
  }


}


const selectFeed=((row)=>{
  //跳转页面并且根据预约单id渲染
  console.log(row)
  /*if (row.isFeed){*/
    router.push({
      path: '/layout/feedback',
      query: {
        name: userStore.user.realname,
        id: userStore.user.counselorid,
        appointmentid:row.appointmentid,
        flag:'true'
      }
    });
  /*}else{
    ElMessage.warning('暂无反馈')
  }*/


})


const userStore=useUserStore()

const assessForm=ref({
  problem:'',
  plan:''
})
const formatStatus=((row)=>{
  if (row.status==='已预约'){
    return 'primary'
  }else if(row.status==='已完成'){
    return 'success'
  }else if (row.status==='已取消'){
    return 'error'
  }
})



onMounted(async ()=>{

  await getList()
})
const getList=(async ()=>{
  const body={
    current:currentPage1.value,
    pageSize:10,
    userid:parseInt(userStore.user.userid)
  }

  let res=await getAppByUserIdService(body)
  if (res.code===200){
    appointmentsFormat(res.data.data)
    total.value=res.data.total
  }
})

const appointmentsFormat=((data)=>{
  data.forEach(item=>{
    //转换星期
    item.weekend=convertToWeekday(item.weekend)

    //转换时间段
    item.times=formatTimeRange(item.startTime,item.endTime)

    //转换状态
    item.status=convertStatus(item.status)

    let str=item.createdat.toString().split('T')
    item.createdat=str[0]+" "+str[1].split(".")[0]

  })
  appointments.value=data


})
function formatTimeRange(startTime, endTime) {
  const startDate = new Date(startTime);
  const endDate = new Date(endTime);

  // 格式化时间为 HH:mm
  const formatTime = (date) => {
    return new Intl.DateTimeFormat('zh-CN', {
      timeZone: "Asia/Shanghai",
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    }).format(date);
  };

  const formattedStartTime = formatTime(startDate);
  const formattedEndTime = formatTime(endDate);

  return `${formattedStartTime} - ${formattedEndTime}`;
}

function convertStatus(status){
  let value=''
  const list=[{
      label:'scheduled',
      value:'已预约',
      type:'primary'
    },
    {
      label:'completed',
      value:'已完成',
      type:'success'
    },
    {
      label:'canceled',
      value:'已取消',
      type:'error'
    },
  ]
  list.forEach(item=>{
    if (item.label==status){
      value=item.value
    }
  })
  return value
}

function convertToWeekday(num) {
  const weekdays = ['星期一', '星期二', '星期三', '星期四', '星期五'];

  // 确保输入在 1 到 5 之间
  if (num >= 1 && num <= 5) {
    return weekdays[num - 1];
  }
}
// 示例预约数据
const appointments = ref([]);

// 取消预约相关的数据
const cancelDialogVisible = ref(false);
const selectedAppointment = ref(null);
const remark = ref('');

const showComplete=ref(false)
// 完成预约函数
const completeBody=ref({})
const completeAppointment = (id) => {
  appointments.value.forEach(item=>{
    console.log(item)
    if (item.appointmentid==id){
      completeBody.value.userid=item.userid
      completeBody.value.appointmentid=item.appointmentid
      completeBody.value.scheduleid=item.scheduleid
      completeBody.value.results=''
    }
  })
  showComplete.value=true
};

const compete=(async ()=>{
  if (!assessForm.value.problem){
    ElMessage.warning("未填写问题点")
  }else if (!assessForm.value.plan){
    ElMessage.warning("未填写解决方案")
  }else {
    completeBody.value.results=JSON.stringify(assessForm.value)
    completeBody.value.userCouID=userStore.user.userid
    let res=await completeService(completeBody.value)
    if (res.code===200){
      ElMessage.success(res.message)
      showComplete.value=false
      await getList()
    }
  }


})

// 显示取消预约对话框
const showCancelDialog = (appointment) => {
  selectedAppointment.value = appointment;
  cancelDialogVisible.value = true;
};

// 取消预约函数
const cancelAppointment = async (id) => {
  if (!remark.value) {
    ElMessage.warning("请填写取消原因")
    return;
  }

  // 在这里处理取消预约的逻辑
  let body={}
  appointments.value.forEach(item=>{
    if (item.appointmentid==id){
      body.appointmentid=item.appointmentid
      body.scheduleid=item.scheduleid
      body.remark=remark.value
      body.userCouID=userStore.user.userid
    }
  })

  const res=await cancelService(body)
  if (res.code===200){

    ElMessage.success(res.message)
    cancelDialogVisible.value = false;
    cancelRemark.value = ''; // 清空备注

    //刷新页面
    await getList()
  }

};

</script>

<style>
.awsCenter {
  display: flex;
  justify-content: center;
  align-items: center;
}
.dialog-footer {
  text-align: right;
}
</style>
